﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using AIS.SDK.Api.Response;
using AIS.SDK.Handler;
using AIS.SDK.Model;
using AISservice.Common;
using AISservice.Entity;
using Common;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json.Linq;


namespace AISservice.Controllers
{
    [Route("api/v1/[controller]/[action]")]
    [ApiController]
    public class P4690Controller : ControllerBase
    {

        [HttpPost]
        public ActionResult<MQResponse> Query([FromBody] P4690param objpram)
        {
            Log4Net.Debug(objpram);
            //P4690param param = Common.JsonHelper.JsonToObject<P4690param>(((Newtonsoft.Json.Linq.JObject)objpram).ToString());
            P4690param param = objpram;
            MQResponse execresult = new MQResponse() { ResponseCode = "200" };
            try
            {
                if (string.IsNullOrWhiteSpace(param.username) || string.IsNullOrWhiteSpace(param.password))
                {
                    throw new MQException("401", "请求的用户名或密码为空！");
                }
                string token = SomeHandler.GetToken(param.username, param.password);
                if (string.IsNullOrWhiteSpace(token))
                {
                    throw new MQException("401", "验证失败，请检查用户名密码是否正确！");
                }

                Console.WriteLine($"查询分组信息");

                FormActionsCollection fs = new FormActionsCollection();
                fs.Add(new FSREvent() { controlID = "1[41]", command = "SetQBEValue", value = param.PRP7 });
                fs.Add(new FSREvent() { controlID = "1[42]", command = "SetQBEValue", value = param.PRP8 });
                fs.Add(new FSREvent() { command = "DoAction", controlID = "15" });

                FormRequest request = new FormRequest()
                {
                    formName = "P4690_W4690A",
                    version = "MCL001",
                    outputType = "VERSION2",
                    stopOnWarning = "fasle",
                    maxPageSize = "1000",
                    formServiceAction = "R",
                    bypassFormServiceEREvent = true,
                    environment = SomeHandler.Getenvironment(param.username),
                    formActions = fs
                };

                FormserviceResponse response = AISClientHandler.Instance.FormserviceV2(token, request);
                if (CommonHandler.ValidateReturnValue(response.JsonString, "fs_P4690_W4690A"))
                {
                    JObject obj = response.ToJObject();
                    int rowcount = Convert.ToInt32(obj["fs_P4690_W4690A"]["data"]["gridData"]["summary"]["records"]);
                    Console.WriteLine($"查询到记录:{rowcount} 条");
                    List<P4690param> lst = new List<P4690param>();

                    //应该查询到数据
                    if (rowcount > 0)
                    {
                        for (int i = 0; i < rowcount; i++)
                        {
                            JObject details = (JObject)obj["fs_P4690_W4690A"]["data"]["gridData"]["rowset"][i];

                            lst.Add(new P4690param() { Itemnumber= details["z_UITM_57"]["value"].ToString() });
                        }
                        execresult.Result = JsonHelper.ObjectToJson(lst);
                        execresult.Message = response.JsonString;
                    }
                }
            }
            catch (MQException x)
            {
                Log4Net.Error($"请求异常:{x.Message}");
                Console.WriteLine($"请求异常:{x.Message}");
                execresult.ResponseCode = CommonHandler.GetException(x.Message, "CODE", x.ExceptionCode).ToString();
                execresult.Message = CommonHandler.GetException(x.Message, "DESC", x.Message).ToString();
            }
            return execresult;
        }
    }
}